//
// Created by DengLibin on 2019/1/9 0009.
//
/**
 * 字符串转数字
 */
#include <iostream>
#include <string>
using namespace std;

/**
 * 字符串转数字
 * @param str
 * @return
 */
int str_to_num_50(string str)
{
    bool flag = false; //是否是负数
    int index = 0; //索引
    int fu_hao_num = 0; //正负号出现的个数
    //头部空格和+判断
    while(str[index] == ' ' || str[index] == '+'){
        if(str[index] == '+'){
            fu_hao_num++;
            index++;
            break;
        }
        index++;
    }
    char c = str[index];
    //-判断
    if(c == '-'){
        flag = true;
        fu_hao_num++;
        index ++;
    }
    //正负号个数
    if(fu_hao_num > 1){
        return 0;
    }
    int startIndex = index; //索引
    int num = 0;//计算有多少位
    while(index < str.length())
    {
        int c = str[index];
        if((c < '0' || c > '9'))
        {
            if(num == 0){ //不是数字开头
                return 0;
            }
            break; //遇到非数字跳出
        }
        num++;
        index++;
    }
    long long sum =0; //返回的数

    for(; num > 0; num--)
    {
        //计算j的值 1,10,100,1000...(权值)
        long long  j = 1;
        for(int i = 0;i < num -1;i++)
        {
            j *=10;
            if(j > INT_MAX){ //越界判断
                break;
            }
        }
        sum += ((str[startIndex]-'0') * j);
        if(sum > INT_MAX){
            break;
        }
        startIndex++;
    }
    if(flag){
        sum =  0 - sum;
    }
    if(sum > INT_MAX){
        sum = INT_MAX;
    }
    if(sum<INT_MIN){
        sum = INT_MIN;
    }
    return sum;
}

int main50(){
    string s = "18446744073709551617";
    int x = str_to_num_50(s);
    cout<< x <<endl;
    return 0;
}